%%
% cd('Y:\Rat Tone Thd Tracking\Results\Tone Thd Tracking - Baseline\');
% cd('Z:\Rat Tone Thd Tracking\Results\Tone Thd Tracking - Baseline\');

% pn = 'C:\Users\djs32\Documents\HRL\PROJECTS\Behavior\Nose-Poke Tone Threshold Tracking\Tone Thd Tracking - Baseline';

% pn = 'H:\Stolzberg\Behavior_Backup\RIG_1\Rat Tone Thd Tracking\Results\Baseline';
pn = 'H:\Stolzberg\Behavior_Backup\RIG_2\Rat Tone Thd Tracking\Results\Baseline';

defpn = cd;

cd(pn);

[fn,pn] = uigetfile({'*.mat','MAT-files (*.mat)'},'Select a file','MultiSelect','on');

cd(defpn);

clear thd

fn = cellstr(fn);

for j = 1:length(fn)
    load(fullfile(pn,fn{j}));
    
    fprintf('%s\n',fn{j});
    
    rv = schedule.response_vals;
    
    fidx = findincell(strfind(schedule.readparams,'ToneFreq'))+1;
    lidx = findincell(strfind(schedule.readparams,'ToneDB'))+1;
    tidx = findincell(strfind(schedule.readparams,'trial_type'))+1;
    ridx = findincell(strfind(schedule.readparams,'response_code'))+1;
    
    ctind = [rv(1:end-1,lidx) == rv(2:end,lidx); 1];
    
    uf = unique(rv(:,fidx));
    uf(isnan(uf)) = [];
    tind = rv(:,tidx) == 0;
    
    ncol = floor(sqrt(length(uf)));
    nrow = ceil(length(uf) / ncol) * 2;
    
    f = findobj('type','figure','-and','name','results');
    if isempty(f)
        f = figure('Name','results','windowstyle','docked');
    end
    figure(f);
    clf(f);
    
    for i = 1:length(uf)
        
        ind = rv(:,fidx) == uf(i) & tind & ~ctind;
        
        SL   = rv(ind,lidx);
        dSL  = diff(SL);
        rind = (dSL(1:end-1) > 0 & dSL(2:end) < 0) | (dSL(1:end-1) < 0 & dSL(2:end) > 0);
        ridx = find(rind) + 1;
        
        thd(i,j) = mean(SL(ridx));
        
        subplot(nrow,ncol,i)
        
        stairs(rv(ind,lidx),'-');
        %     plot(rv(ind,lidx),'-o');
        hold on
        plot(ridx,SL(ridx),'o','linestyle','none','markerfacecolor','r');
        plot(xlim,[thd(i) thd(i)],'-c');
        hold off
        xlim([0 sum(ind)]);
        ylim([-20 50]);
        title(num2str(uf(i),'%d Hz'));
        
    end
    
    subplot(nrow,ncol,i+1:nrow*ncol);
    if length(uf) ~= size(thd,1)
        uf(end+1:size(thd,1)) = nan;
    end
    plot(uf,thd,'-o');
    hold(gca,'on');
    plot(uf,nanmean(thd,2),'-k','linewidth',3);
    hold(gca,'off');
    set(gca,'xscale','log','xlim',[900 35200], ...
        'xtick',round(uf/1000));
    xlabel('Frequency (kHz)');
    ylabel('Sound Level (dB SPL)');
end



% results = [uf thd(:)];
% openvar results
cs = repmat('%d\t',1,size(thd,2));
s  = sprintf([cs '\n'],thd');
clipboard('copy',s);
